#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WebSocket相关路由
"""

from flask import request, jsonify
from flask_socketio import emit

from utils import setup_console_encoding

from logging_config import get_logger

# 设置控制台编码
setup_console_encoding()

logger = get_logger(__name__)


def register_websocket_events(socketio):
    """注册WebSocket事件处理器"""
    
    @socketio.on('connect')
    def handle_connect():
        """客户端连接"""
        try:
            logger.info(f"客户端连接: session_id={request.sid}")
            emit('connected', {'message': '连接成功'})
        except Exception as e:
            logger.error(f"连接处理错误: {e}")
    
    @socketio.on('disconnect')
    def handle_disconnect():
        """客户端断开连接"""
        try:
            logger.info(f"客户端断开连接: session_id={request.sid}")
        except Exception as e:
            logger.error(f"断开连接处理错误: {e}")
    
    @socketio.on('join_meeting')
    def handle_join_meeting(data):
        """加入会议"""
        try:
            logger.info(f"客户端加入会议: session_id={request.sid}, data={data}")
            emit('joined_meeting', {'message': '已加入会议'})
        except Exception as e:
            logger.error(f"加入会议处理错误: {e}")
            emit('error', {'message': '加入会议失败', 'error': str(e)})
    
    @socketio.on('error')
    def handle_error(error):
        """处理错误"""
        try:
            logger.error(f"WebSocket错误: session_id={request.sid}, error={error}")
            emit('error', {'message': '发生错误', 'error': str(error)})
        except Exception as e:
            logger.error(f"错误处理失败: {e}")
    
    @socketio.on_error_default
    def default_error_handler(e):
        """默认错误处理器"""
        logger.error(f"WebSocket默认错误处理: {e}")
        try:
            emit('error', {'message': '系统错误', 'error': str(e)})
        except:
            pass  # 如果emit也失败，就忽略
    
    logger.info("WebSocket事件处理器注册完成")


def register_websocket_routes(app):
    """注册WebSocket相关的HTTP路由"""
    
    @app.route('/websocket/health')
    def websocket_health():
        """WebSocket健康检查"""
        try:
            return jsonify({
                'status': 'healthy',
                'websocket': 'available',
                'message': 'WebSocket服务正常'
            })
        except Exception as e:
            logger.error(f"WebSocket健康检查失败: {e}")
            return jsonify({
                'status': 'error',
                'websocket': 'unavailable',
                'message': f'WebSocket服务异常: {str(e)}'
            }), 500
